<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面板 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click="searchUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="userList"
        border
        stripe
        style="width: 100%">
        <el-table-column type="index" label="序号" width="180">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="创建时间">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope='scope'>
            <el-switch
              v-model="scope.row.mg_state"
              @change='userStateChange(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="260px">
          <template slot-scope='scope'>
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editOpen(scope.row)"></el-button>
            <el-button type="danger"  icon="el-icon-delete" size="mini" @click="delUser(scope.row)"></el-button>
            <el-tooltip  effect="dark" content="分配角色" placement="top" enterable>
              <el-button type="warning" icon="el-icon-star-off"  size="mini"  @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
    <el-dialog
      title="新增用户"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-form  :model="addForm" :rules="rules" ref="addForm" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input type="mobile" v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="编辑用户"
      :visible.sync="editFlag"
      width="30%"
      :before-close="editHandleClose">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input type="mobile" v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editHandleClose">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close='setRoleDialogClose'
      >
      <p>当前用户：{{userInfo.username}}</p>
      <p>当前角色：{{userInfo.role_name}}</p>
      <P>
        分配新角色:
        <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
      </P>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getUsersList, userStateUpdata, createUser, editUser, delUser, saveUserRole } from '@/api/users'
import { getRolesList } from '@/api/roles'
import { userNameValidate, passwordValidate, emailValidate, phoneValidate } from '@/validate/validate'
export default {
  name: 'Users',
  data () {
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userInfo: {

      },
      selectRoleId: '',
      userList: [],
      rolesList: [],
      total: 0,
      dialogVisible: false,
      setRoleDialogVisible: false,
      editFlag: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: null,
        username: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, validator: userNameValidate, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: passwordValidate, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: emailValidate, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: phoneValidate, trigger: 'blur' }
        ]
      },
      editRules: {
        email: [
          { required: true, validator: emailValidate, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: phoneValidate, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await getUsersList(this.queryInfo)
      if (res.meta.status === 200) {
        this.total = res.data.total
        this.userList = JSON.parse(JSON.stringify(res.data.users))
      }
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },
    async userStateChange (info) {
      const { data: res } = await userStateUpdata(info)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
      } else {
        this.$message.console.error(res.meta.msg)
        info.mg_state = !info.mg_state
      }
    },
    searchUsers () {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    addUser () {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await createUser(this.editForm)
        if (res.meta.status === 201) {
          this.handleClose()
          this.$message.success(res.meta.msg)
          this.getUserList()
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    handleClose () {
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
    },
    editOpen (info) {
      this.editFlag = true
      for (var key in this.editForm) {
        for (var k in info) {
          if (key === k) {
            this.editForm[key] = info[key]
          }
        }
      }
    },
    editHandleClose () {
      this.editFlag = false
      this.$refs.editForm.resetFields()
    },
    editUser () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await editUser(this.editForm)
        if (res.meta.status === 200) {
          this.editHandleClose()
          this.$message.success(res.meta.msg)
          this.getUserList()
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    delUser (info) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await delUser(info.id)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.getUserList()
        } else {
          this.$message.success(res.meta.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async setRole (row) {
      this.userInfo = row
      const { data: res } = await getRolesList()
      if (res.meta.status === 200) {
        this.rolesList = res.data
      }
      this.setRoleDialogVisible = true
    },
    async saveRole () {
      const params = {
        userId: this.userInfo.id,
        roleId: this.selectRoleId
      }
      const { data: res } = await saveUserRole(params)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.setRoleDialogVisible = false
        this.userInfo = {}
        this.selectRoleId = ''
        this.getUserList()
      } else {
        this.$message.success(re.meta.msg)
      }
    },
    setRoleDialogClose () {
      this.userInfo = {}
      this.selectRoleId = ''
    }
  }
}
</script>
<style lang="less" scoped>

</style>
